const userModel = require('../models/user');

class UserController {
    /**
     * 创建用户
     */

    static async create(ctx) {
      
        let {
            openid,
            nickname,
            headimg,
            gender
        } = ctx.request.body

        let params = {
            openid,
            nickname,
            headimg,
            gender
        }
     
        //  查询用户是存在
        const existUser = await userModel.findUser(params.openid);
        if (existUser) {
            ctx.response.status =  403;
            ctx.body = {
                code: 403,
                message: '用户已存在'
            }
        } else {
            try {
                await userModel.create(params);
                const newUser = await userModel.findUser(params.openid);
                console.log(newUser);
                ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    message: '创建用户成功',
                    data: newUser
                }
            } catch (err) {
                ctx.response.status = 500;
                ctx.body = {
                    code: 500,
                    message: err
                }
            }
        }
    }

    /**
     * 登录
     */

    static async login (ctx) {
      console.log(ctx);
      return false;
    }

    /**
     * 获取用户列表
     */
    static async getUserList(ctx) {
        let userList = ctx.request.body;
        if (userList) {
            const data = await userModel.findAllUserList();
            ctx.response.status = 200;
            ctx.body = {
                code: 200,
                msg: '查询成功',
                data
            }
        } else {
            ctx.response.status = 412;
            ctx.body = {
                code: 412,
                msg: '查询失败',
                data
            }
        }
    }

    /**
     * 获取用户
     */
     
    static async getUser(ctx){
        try {
            let openid = ctx.request.query.openid;
            const data = await userModel.findUser(openid);
            ctx.response.status = 200;
            ctx.body = {
                code: 200,
                msg: '查询成功',
                data
            }
        } catch (err) {
            ctx.response.status = 500;
            ctx.body = {
                code: 500,
                message: err
            }
        }
    }
}
module.exports = UserController